<template>
  <div class="register-container">
    <h1>注册</h1>
    <form @submit.prevent="register" class="register-form">
      <input v-model="registerUsername" placeholder="用户名" class="register-input" />
      <input v-model="registerPassword" type="password" placeholder="密码" class="register-input" />
      <button type="submit" class="register-button">注册</button>
    </form>
    <div v-if="registerMessage" class="register-message">{{ registerMessage }}</div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';
import { useRouter } from 'vue-router';

const router = useRouter();

const registerUsername = ref('');
const registerPassword = ref('');
const registerMessage = ref('');

const register = async () => {
  try {
    const response = await axios.post('http://127.0.0.1:5000/register', { username: registerUsername.value, password: registerPassword.value });
    registerMessage.value = response.data.message;
    router.push('/UserLogin');
  } catch (error) {
    if (error.response) {
      registerMessage.value = error.response.data.error;
    } else {
      registerMessage.value = '请求出错，请稍后再试';
    }
  }
};
</script>

<style scoped>
@import "../styles/UserRegister.css";
</style>